package gui;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import model.User;
import actions.MyCloseActionHandler;

@SuppressWarnings("serial")
public class MyTabbedPane extends JTabbedPane {
	private ArrayList<ChatTab> chatTabs = new ArrayList<ChatTab>();
	
	public MyTabbedPane(int top) {
		super();
	}

	public MyTabbedPane() {
		super();
		// TODO Auto-generated constructor stub
	}



	public MyTabbedPane(int tabPlacement, int tabLayoutPolicy) {
		super(tabPlacement, tabLayoutPolicy);
		// TODO Auto-generated constructor stub
	}

	public int myAddTab(String title, Component component) {
		super.addTab(title, component);
		
		
		int index = this.indexOfTab(title);
		JPanel pnlTab = new JPanel(new GridBagLayout());
		pnlTab.setOpaque(false);
		JLabel lblTitle = new JLabel(title);
		TabButton btnClose = new TabButton();

		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 1;

		pnlTab.add(lblTitle, gbc);

		gbc.gridx++;
		gbc.weightx = 0;
		pnlTab.add(btnClose, gbc);


		MyCloseActionHandler myCloseActionHandler=new MyCloseActionHandler(title);
		this.setTabComponentAt(index, pnlTab);
		//autoselekt novootvorenog taba
		//this.setSelectedIndex(index);
		btnClose.addActionListener(myCloseActionHandler);
		
		if(component instanceof ChatTab) {
			chatTabs.add((ChatTab) component);
		}
		return index;
	}
	
	@Override
	public void addTab(String title, Component component) {
		// TODO Auto-generated method stub
		super.addTab(title, component);
		if(component instanceof ChatTab) {
			chatTabs.add((ChatTab) component);
		}
	}
	
	public User getCurrentUser() {
		return chatTabs.get(getSelectedIndex()).getChatWith();
	}
	
	public ChatTab getCurrentChatTab() {
		return chatTabs.get(getSelectedIndex());
	}
	
	@Override
	public void removeTabAt(int index) {
		chatTabs.remove(index);
		super.removeTabAt(index);
	}
	
	public ChatTab getTabWithUser(User user) {
		if(user==null) return null;
		ChatTab retVal = null;
		for(ChatTab ct : chatTabs) {
			if(user.equals(ct.getChatWith()))
					retVal=ct;
		}
		return retVal;
	}

	public ArrayList<ChatTab> getChatTabs() {
		return chatTabs;
	}
}
